﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for EnumUtility
/// </summary>
public static class EnumUtility
{
    /// <summary>
    /// display an enum's nice name, which comes from [Description("Nice name")] tag before enum value
    /// </summary>
    /// <param name="value">enum value to get nice name</param>
    /// <returns>enum's nice name, or its original value if Description tag not defined</returns>
    public static string GetEnumNiceName(Enum value)
    {
        System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());

        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }

    /// <summary>
    /// returns a list (IEnumerable) of specific Enum name, useful to use in DropDownList
    /// </summary>
    /// <typeparam name="T">Enum name</typeparam>
    /// <returns>list (IEnumerable) of specific Enum name</returns>
    public static IEnumerable<T> EnumToList<T>()
    {
        Type enumType = typeof(T);

        // Can't use generic type constraints on value types,
        // so have to do check like this
        if (enumType.BaseType != typeof(Enum))
            throw new ArgumentException("T must be of type System.Enum");

        Array enumValArray = Enum.GetValues(enumType);
        List<T> enumValList = new List<T>(enumValArray.Length);

        foreach (int val in enumValArray)
        {
            enumValList.Add((T)Enum.Parse(enumType, val.ToString()));
        }

        return enumValList;
    }
}